$(function() {
    $( "input[type=submit], input[type=button], a.button, button" ).button();

	$( document ).tooltip();

	if ($('.currency').length > 0 ){
		 // Money format with currency sign
		 $('.currency').attr('data-a-sep', "." ).attr('data-a-dec', "," ).attr('data-a-sign', "€" );
		 $('.currency').autoNumeric('init');
	}

	if ($('.multiAutocomplete').length > 0 ){
		multiAutocomplete($('.multiAutocomplete'));
	}



	// portlets
	$( ".column" ).sortable({
      connectWith: ".column"
    });
    $( ".portlet" ).addClass( "ui-widget ui-widget-content ui-helper-clearfix ui-corner-all" )
      .find( ".portlet-header" )
        .addClass( "ui-widget-header ui-corner-all" )
        .prepend( "<span class='ui-icon ui-icon-minusthick'></span>")
        .end()
      .find( ".portlet-content" );
    $( ".portlet-header .ui-icon" ).click(function() {
      $( this ).toggleClass( "ui-icon-minusthick" ).toggleClass( "ui-icon-plusthick" );
      $( this ).parents( ".portlet:first" ).find( ".portlet-content" ).toggle();
    });
    $( ".column" ).disableSelection();



});


	 
function multiAutocomplete(field) {

	var dataOptions = $(field).data('options');
	var availableTags = dataOptions.split(',');

	function split( val ) {
	  return val.split( /,\s*/ );
	}
	function extractLast( term ) {
	  return split( term ).pop();
	}
 
	$( field )
	  // don't navigate away from the field on tab when selecting an item
	  .bind( "keydown", function( event ) {
		if ( event.keyCode === $.ui.keyCode.TAB &&
			$( this ).data( "ui-autocomplete" ).menu.active ) {
		  event.preventDefault();
		}
	  })
	  .autocomplete({
		minLength: 0,
		source: function( request, response ) {
		  // delegate back to autocomplete, but extract the last term
		  response( $.ui.autocomplete.filter(
			availableTags, extractLast( request.term ) ) );
		},
		focus: function() {
		  // prevent value inserted on focus
		  return false;
		},

		change: function( event, ui ) {
		  if ( !ui.item ) {
			var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i" ), valid = false;
			for (var i=0; i<availableTags.length; i++)
			{
				if (availableTags[i].match(matcher)) {
					this.selected = valid = true;
					return false;
				}
			}
			if (!valid) {
			  // remove invalid value, as it didn't match anything
			  var value = $(this).val();
			  var lastCommaPosition = value.lastIndexOf(',');
			  var validValue = value.substring(0, lastCommaPosition);
			  $(this).val(validValue);
			  return false;
			}
		  }
		},


		select: function( event, ui ) {
		  var terms = split( this.value );
		  // remove the current input
		  terms.pop();
		  // add the selected item
		  terms.push( ui.item.value );
		  // add placeholder to get the comma-and-space at the end
		  terms.push( "" );
		  this.value = terms.join( ", " );
		  return false;
		}
	  });
}
